package com.naiterui.ehp.bp.support.bean.ser;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.naiterui.ehp.bp.support.bean.annotation.Fen2Yuan;

public class Fen2YuanFieldDeserialize extends StdScalarDeserializer<Integer> implements ContextualDeserializer {

    private static final long serialVersionUID = -2909950705208627722L;
    private final String pattern;

    @SuppressWarnings("unused")
    public Fen2YuanFieldDeserialize() {
        super(Integer.class);
        this.pattern = "##0.00";
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        Fen2Yuan fen2Yuan = property.getAnnotation(Fen2Yuan.class);
        if (fen2Yuan != null) {
            return new Fen2YuanFieldDeserialize();
        }
        return null;
    }

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        DecimalFormat df = new DecimalFormat(this.pattern);

        return new BigDecimal(df.format(new BigDecimal(p.getText()).multiply(new BigDecimal(100)))).intValue();
    }

}
